import React, {useCallback, useEffect, useMemo, useState} from "react"
import {Pageable} from "../../utils/Page";
import {
    createGoodsCategory,
    deleteGoodsCategory, QueryGoodsCategoriesResponse,
    updateGoodsCategory
} from "../../apis/GoodsCategoriesApi";
import AuthorizationResource from "../../components/AuthorizationResource";
import {Button, ConfigProvider, Form, Input, Space, Table} from "antd";
import {DeleteOutlined, EditOutlined, PlusOutlined} from "@ant-design/icons";
import {castFilterValue, mergePaginationAndPageable, useTableSearchTextColumnProps} from "../../utils/AntdTableUtils";
import DataPageLayout from "../../components/DataPageLayout";
import FormDrawer from "../../components/FormDrawer";
import {queryGoodsCategories} from "../../apis/GoodsCategoriesApi";
import {DashboardPage} from "../../components/dashboardPages/DashboardPage";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import LoadableButton from "../LoadableButton";
import {deleteGoodsBrand} from "../../apis/GoodsBrandsApi";

export interface GoodsCategoryProps {

}

export interface GoodsCategoryFormData {
    name: string
}

const GoodsCategoriesPage: React.FC<GoodsCategoryProps> = (props) => {
    const [openAddDrawer, setOpenAddDrawer] = useState(false)
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryGoodsCategoriesResponse[]>([])
    const [searchNameText, setSearchNameText] = useState<string>()
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)

    const query = useCallback(()=>{
        setLoading(true)
        return queryGoodsCategories({name: searchNameText,}, pageable).then(response => {
            setTotalElements(response.data.totalElements)
            setData(response.data.content)
        }).finally(() => {
            setLoading(false)
        })
    },[...pageable.toDependencyList(), searchNameText,])

    // noinspection DuplicatedCode
    const [editGoodsId, setEditingItemId] = useState<number>()
    const editingItem = useMemo(() => {
        return data.find(it => it.id === editGoodsId)
    }, [editGoodsId,data]);

    useEffect(() => {
        query()
    }, [query]);
    let nameSearchProps = useTableSearchTextColumnProps<QueryGoodsCategoriesResponse>("name", {
        placeholder: "名称"
    });

    function buildFormItems() {
        return <>
            <Form.Item label={"名称"} name="name" rules={[{required: true}]}>
                <Input/>
            </Form.Item>
        </>
    }

    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["货品_分类_新增"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>新增分类</Button>
        </AuthorizationResource>}>
            <ConfigProvider componentSize={"small"}>
                <Table loading={loading} dataSource={data} rowKey={"id"} pagination={{
                    current: pageable.page,
                    pageSize: pageable.size,
                    total: totalElements,
                }} onChange={(pagination, filters, sorter) => {
                    setSearchNameText(castFilterValue(filters.name))
                    setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                }}>
                    <Table.Column dataIndex={"name"} title={"名称"} {...nameSearchProps}/>
                    <Table.Column dataIndex={"goodsAmount"} title={"商品数量"}/>
                    <Table.Column<QueryGoodsCategoriesResponse> title={"操作"} render={(_, item) => {
                        return <Space>

                            {employeeAuthorizationStore.hasAuthority("货品_分类_修改")
                                && <Button type={"link"}
                                           onClick={() => {
                                               setEditingItemId(item.id)
                                           }}>
                                    <EditOutlined/>
                                </Button>
                            }
                            {employeeAuthorizationStore.hasAuthority("货品_分类_删除") && !item.goodsAmount
                                && <LoadableButton type={"link"}
                                                   danger
                                                   onClick={async () => {
                                                       await deleteGoodsCategory(item.id)
                                                       await query()
                                                   }}>
                                    <DeleteOutlined/>
                                </LoadableButton>
                            }
                        </Space>
                    }}/>
                </Table>
            </ConfigProvider>
        </DataPageLayout>
        <FormDrawer<GoodsCategoryFormData> onClose={() => setOpenAddDrawer(false)}
                                           title={"新增分类"}
                                           onConfirm={async (values) => {
                                               return createGoodsCategory(values).then(() => {
                                                   setOpenAddDrawer(false)
                                                   query()
                                               })
                                           }}
                                           open={openAddDrawer}>
            {buildFormItems()}
        </FormDrawer>
        <FormDrawer<GoodsCategoryFormData> open={!!editingItem} title={"修改分类"} onClose={() => {
            setEditingItemId(undefined)
        }} onConfirm={async (values) => {
            return updateGoodsCategory(editGoodsId!!, values).then(() => {
                query()
                setEditingItemId(undefined)
            })
        }} initialValues={editingItem}>
            {buildFormItems()}
        </FormDrawer>
    </>
}
export default observerDashboardPageWrapper(GoodsCategoriesPage,"goods/categories","货品分类")